// 查查用户信息

// 配置
const searchConfig = {
  0:  (params) => {
    return new Promise( async (resolve, reject) => {
      const allSql = `SELECT * FROM users LIMIT ? OFFSET ?`;
      const pageNumT = params.pageNum || 1;
      const rowT = params.row || 10;
      const { connection} = params
    try {
      const [results, fie] = await connection.query(allSql, [rowT * 1, (pageNumT - 1) * rowT])
      resolve(results);
    }
    catch (error) {
      reject({
        error,
        message: '查询所有用户信息失败'
      });
    }
    })

  },
  1: (params) => {
    return new Promise( async (resolve, reject) => {
      const { id, pageNum, row, connection } = params;
      const pageNumT = pageNum || 1;
      const rowT = row || 10;
      const idSearchSql = `SELECT * FROM users WHERE id = ?LIMIT ? OFFSET ?`;
    try {
      const [results, fie] = await connection.query(idSearchSql, [id, rowT * 1, (pageNumT - 1) * rowT])
      resolve(results);
    }
    catch (error) {
      reject({
        error,
        message: '依据ID查询用户信息失败'
      });
    }
    
  })
},
  2: (params) => {
    return new Promise( async (resolve, reject) => {
      const { userName, pageNum, row, connection } = params;
      const pageNumT = pageNum || 1;
      const rowT = row || 10;
      const userNameSearchSql = `SELECT * FROM users WHERE userName LIKE ? LIMIT ? OFFSET ?`;
     try {
      const [result, fie] = await connection.query(userNameSearchSql, [`%${userName}%`, rowT * 1, (pageNumT - 1) * rowT ])
      resolve(result);
     }
     catch (error) {
       reject({
         error,
         message: '依据用户名查询用户信息失败'
       });
     }
    }) 
  },
  3: (params) => {
    return new Promise( async (resolve, reject) => {
      const { pageNum, row, id, userName, connection} = params;
      const pageNumT = pageNum || 1;
      const rowT = row || 10; 
      const idSearchSql = `SELECT * FROM users WHERE id =? AND userName = ? LIMIT ? OFFSET ?`;
      try {
        const [results, fie] = await connection.query(idSearchSql, [id, userName, rowT * 1, (pageNumT - 1) * rowT])
        resolve(results);
      }
      catch (error) {
        reject({
          error,
          message: '依据ID和用户名查询用户信息失败'
        });
      }
    }) 
  }
}

const totleConfig = {
  0:  (params) => {
      return new Promise( async (resolve, reject) => {
        const allSql = `SELECT COUNT(*) AS total FROM users`;
        const { connection} = params
      try {
        const [results, fie] = await connection.query(allSql)
        const [ { total } ] = results
        resolve(total);
      }
      catch (error) {
        reject({
          error,
          message: '查询所有用户信息总数失败'
        });
      } 
  }) 
   
  },
  1: (params) => {
    return new Promise( async (resolve, reject) => {
      const { id, connection } = params;
      const idSearchSql = `SELECT COUNT(*) AS total FROM users WHERE id = ?`; 
    try {
      const [results, fie] = await connection.query(idSearchSql, [id])
      const [ { total } ] = results
      resolve(total);       
    }
    catch (error) {
      reject({
        error,
        message: '依据ID查询用户信息总数失败'
      });
    } 
  })
},
  2: (params) => {
    return new Promise( async (resolve, reject) => {
      const { userName, connection } = params;
      const userNameSearchSql = `SELECT COUNT(*) AS total FROM users WHERE userName LIKE?`; 
      try {
        const [results, fie] = await connection.query(userNameSearchSql, [`%${userName}%`])
        const [ { total } ] = results
        resolve(total);
      }
      catch (error) {
        reject({
          error,
          message: '依据用户名查询用户信息总数失败'
        });
      }
    }) 
  },
  3: (params) => {
    return new Promise( async (resolve, reject) => {
      const { id, userName, connection } = params;
      const idSearchSql = `SELECT COUNT(*) AS total FROM users WHERE id = ? AND userName = ?`;
      try {
        const [results, fie] = await connection.query(idSearchSql, [id, userName])
        const [ { total } ] = results
        resolve(total);
      }
      catch (error) {
        reject({
          error,
          message: '依据ID和用户名查询用户信息总数失败'
        });
      } 
    }) 
  }
}


/**
 * 此函数用于根据传入参数中的id和userName进行判断，并返回相应的标识值。
 * @param {Object} param - 包含id和userName的对象。
 * @returns {number} - 根据条件返回不同的值：1表示存在id，2表示存在userName，0表示两者都不存在。
 */
function assertZreo(param) {
  // 从传入的参数对象中解构出id和userName
  const { id, userName } = param;
  // 如果id存在，则返回1
  if( id ) return 1 
  // 如果userName存在，则返回2
  else if(userName) return 2
  // 如果id和userName都不存在，则返回0
  return 0
}


function createSendData( result, total, pageNum, row ) {
  const sendData = {
    total: total,
    list: result,
    pageNum: pageNum || 1,
    row: row || 10
  }
  return sendData
}


// 依据用户名查询用户信息 
module.exports.accToUesrNameSelectUser = function accToUesrNameSelectUser(params) {
  return new Promise( async(resolve, reject) => {
    const { userName, connection}= params;
    const userNameSearchSql = `SELECT * FROM users WHERE userName =?`;
    try {
      const [rows] = await connection.query(userNameSearchSql, [userName]);
      resolve(rows);
    }
    catch (error) {
      reject({
        error,
        message: '依据用户名查询用户信息失败'
      });
    }
  })
}




module.exports.searchUser = async function(req, res, next) {
  const { id, userName, pageNum, row} = req.query;
  const connection = req.connection;
  try {
    const [ result, total ] = await Promise.all([
      searchConfig[assertZreo({ id, userName, pageNum,row })]({ id, userName, pageNum, row,connection }),
      totleConfig[assertZreo({ id, userName })]({ id, userName, connection }) 
    ])

    if( Array.isArray(result) && result.length > 0) {
      return res.resend.sendJson(req, res,{
        status: 200,
        code: 'SUCCESS', 
        data: createSendData(result, total, pageNum, row,),
        msg: '查询注册用户信息成功'
      })      
    }
    return res.resend.sendJson(req, res,{
      status: 200,
      code: 'SUCCESS',
      data: createSendData([], 0, pageNum, row),
      msg: '查询注册用户信息成功'
    })
  }
  catch (error) {
    return res.resend.sendJson(req, res,{
      status: 500,
      code: 'FAIL',
      data: '',
      logMsg: error.error,
      msg: error.message
    })
  }
}